package com.lcxw.hxzbadmin.configcontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import com.obs.services.ObsClient;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.PutObjectResult;
import com.obs.services.model.TemporarySignatureRequest;
import com.obs.services.model.TemporarySignatureResponse;
import java.io.ByteArrayInputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import com.lcxw.hxzbadmin.entity.configbean.YwpdAnnounce;
import com.lcxw.hxzbadmin.service.configservice.AnnounceService;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbcommon.common.ObsUtil;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.CommonBean;

/**
 * 系统公告
 */

@RestController
@RequestMapping("/admin/announce")
@CrossOrigin
public class AnnounceController {
    private Logger logger = LoggerFactory.getLogger(AnnounceController.class);

    @Resource
    AnnounceService announceService;

    private static ObsClient obsClient = new ObsUtil()
        .getObsClient();

    @PostMapping("/delete")
    public Response deleteAnnounce(@RequestBody JSONObject requestParams){
        logger.info("admin {} delete a announce:{}",requestParams.getString("adminName"),requestParams.getInteger("id"));

        announceService.deleteByPrimaryKey(requestParams.getInteger("id"));

        return Response.ok();
    }

    @PostMapping("/add")
    public Response addAnnounce(@RequestBody JSONObject requestParams){
        YwpdAnnounce ywpdAnnounce = new YwpdAnnounce();

        ywpdAnnounce.setTitle(requestParams.getString("title"));
        ywpdAnnounce.setContent(requestParams.getString("content"));
        ywpdAnnounce.setFengMian(requestParams.getString("fengMian"));
        ywpdAnnounce.setZhuangTai(requestParams.getString("zhuangTai"));

        ywpdAnnounce.setAddTime(StringUtil.getDateTime());

        announceService.insert(ywpdAnnounce);

        return Response.ok();
    }

    @PostMapping("/getAll")
    public Response getAllAnnounce(@RequestBody JSONObject requestParams){
        List<YwpdAnnounce> data = announceService.selectAll();

        return Response.ok(data);
    }

    @PostMapping("/mod")
    public Response modAnnounce(@RequestBody JSONObject requestParams){
        int id = requestParams.getInteger("id");

        YwpdAnnounce ywpdAnnounce = announceService.selectById(id);

        ywpdAnnounce.setTitle(requestParams.getString("title"));
        ywpdAnnounce.setContent(requestParams.getString("content"));
        ywpdAnnounce.setFengMian(requestParams.getString("fengMian"));
        ywpdAnnounce.setZhuangTai(requestParams.getString("zhuangTai"));

        announceService.updateByPrimaryKey(ywpdAnnounce);

        return Response.ok();
    }

    @PostMapping("/img/upload")
    public Response uploadCarousel(@RequestBody JSONObject requestParams){

        if (StringUtil.isEmpty(requestParams.getString("img"))) {
            logger.error("{} set img failed,because img info is null",
                requestParams.getString("userId"));
            return Response.common(logger,"img is null.", ErrorCode.PARAM_ERROR,"img must not be null",null);
        }

        String giftName = requestParams.getString("giftName");
        String imgName = "announce/" + giftName + "announce.png";
        String imgOrigin = requestParams.getString("img");

        return upload(imgOrigin,imgName);
    }

    private Response upload(String imgOrigin,String imgName) {
        byte[] imgBytes;
        try {
            //拿到前台传过来的img图片的原始数据
            //对原始数据解码，获得字节数组
            imgBytes = new BASE64Decoder().decodeBuffer(imgOrigin);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("decrypt failed");
            return Response.common(logger,"decrypt failed",ErrorCode.INTERNAL_ERROR,"internal failed",null);
        }

        PutObjectResult putObjectResult = obsClient
            .putObject("ywpd-picture", imgName, new ByteArrayInputStream(imgBytes));

        //判断是否上传到华为OBS失败
        if (null == putObjectResult) {
            logger.error("put img to obs failed");
            return Response.common(logger,"put img to obs failed",ErrorCode.EXTERNAL_ERROR,"internal error",null);
        }

        //上传成功后，需要获取该图片的下载url
        //生成头像url的过期时间，设置为10年
        long expireSeconds = CommonBean.IMGEXPIREDTIME;

        //下面是生成头像URL的方法
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET,
            expireSeconds);
        request.setBucketName("ywpd-picture");
        request.setObjectKey(imgName);
        TemporarySignatureResponse temporarySignatureResponse = obsClient
            .createTemporarySignature(request);
        String imgUrl = temporarySignatureResponse.getSignedUrl();

        Map<String,Object> data = new LinkedHashMap<>();
        data.put("imgUrl",imgUrl);

        return Response.common(logger,"upload gift img success.",0,"success",data);
    }

}
